﻿using Engine;
using Engine.Graphics;
using GameEntitySystem;
using TemplatesDatabase;

namespace Game
{
    public class ItemDisPlay : Component, IDrawable, IUpdateable
    {
        public PrimitivesRenderer3D m_primitivesRenderer3D = new PrimitivesRenderer3D();

        public ComponentHealth componentHealth;

        public ComponentCreature m_componentCreature;

        public SubsystemTerrain m_subsystemTerrain;

        public static int[] m_drawOrders = new int[1] { 2001 };

        public int DrawBlockValue;

        public UpdateOrder UpdateOrder => UpdateOrder.Default;

        public int[] DrawOrders => m_drawOrders;

        public void Draw(Camera camera, int drawOrder)
        {
            Block block = BlocksManager.Blocks[DrawBlockValue];
            Vector3 position = m_componentCreature.ComponentBody.Position;
            Point3 point = new Point3(position);
            Matrix matrix = m_componentCreature.ComponentBody.Matrix * Matrix.CreateTranslation(0f, 1f, 0f);
            DrawBlockEnvironmentData drawBlockEnvironmentData = new DrawBlockEnvironmentData();
            drawBlockEnvironmentData.DrawBlockMode = DrawBlockMode.ThirdPerson;
            drawBlockEnvironmentData.InWorldMatrix = matrix;
            drawBlockEnvironmentData.Humidity = m_subsystemTerrain.Terrain.GetSeasonalHumidity(point.X, point.Z);
            drawBlockEnvironmentData.Temperature = m_subsystemTerrain.Terrain.GetSeasonalTemperature(point.X, point.Z) + SubsystemWeather.GetTemperatureAdjustmentAtHeight(point.Y);
            drawBlockEnvironmentData.Light = m_subsystemTerrain.Terrain.GetCellLight(point.X, point.Y, point.Z);
            drawBlockEnvironmentData.BillboardDirection = -Vector3.UnitZ;
            drawBlockEnvironmentData.SubsystemTerrain = m_subsystemTerrain;
            int value = Terrain.MakeBlockValue(DrawBlockValue);
            block.DrawBlock(m_primitivesRenderer3D, value, Color.White, 1f, ref matrix, drawBlockEnvironmentData);
            FlatBatch3D flatBatch3D = m_primitivesRenderer3D.FlatBatch();
            m_primitivesRenderer3D.Flush(camera.ViewProjectionMatrix);
        }

        public void Update(float dt)
        {
        }

        public override void Load(ValuesDictionary valuesDictionary, IdToEntityMap idToEntityMap)
        {
            DrawBlockValue = valuesDictionary.GetValue<int>("DrawBlockValue");
            componentHealth = base.Entity.FindComponent<ComponentHealth>(throwOnError: true);
            m_componentCreature = base.Entity.FindComponent<ComponentCreature>(throwOnError: true);
            m_subsystemTerrain = base.Project.FindSubsystem<SubsystemTerrain>(throwOnError: true);
        }

        public override void Save(ValuesDictionary valuesDictionary, EntityToIdMap entityToIdMap)
        {
            base.Save(valuesDictionary, entityToIdMap);
            valuesDictionary.SetValue("DrawBlockValue", DrawBlockValue);
        }
    }
}